import pika
import threading


class MQConnection:
    _instance = None
    _lock = threading.Lock()

    def __new__(cls):
        with cls._lock:
            if not cls._instance:
                cls._instance = super().__new__(cls)
                cls._instance._init_connection()
            return cls._instance

    def _init_connection(self):
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(
                host='192.168.122.173',
                heartbeat=600,
                blocked_connection_timeout=300
            )
        )
        self.channel = self.connection.channel()

        # 声明请求队列
        self.channel.queue_declare(
            queue='rpc_requests',
            durable=True,
            arguments={'x-max-priority': 10}
        )

        # 声明响应队列
        self.channel.queue_declare(
            queue='rpc_replies',
            durable=True,
            arguments={'x-max-priority': 10}
        )

    def get_channel(self):
        if self.connection.is_closed:
            self._init_connection()
        return self.channel
